import os
from testrailRobot import *
from datetime import datetime
from collections import Counter

def add_case_id(dirpath):
    all_cases = CommonFunctions().get_all_cases_in_sections_parallel()
    for dirpath, dirnames, filenames in os.walk(dirpath):
        for filename in filenames:
            if filename.endswith(".robot") and filename!="__init__.robot":
                #todo 
                format_filename = filename.lstrip("001__")
                index = next((index for index, case in enumerate(all_cases) if case['title']+".robot" == format_filename), None)
                if index is not None:
                    ID = all_cases[index]['id']
                    robot_filename = os.path.join(dirpath,filename)
                    with open(robot_filename, 'r',encoding='utf-8') as fileobj:
                        lines = fileobj.readlines()
                        # Insert the new line at the third position
                    lines.insert(1, f"Metadata    ID    {ID}\n")
                    # Write the updated contents back to the file
                    with open(robot_filename, 'w',encoding='utf-8') as file:
                        file.writelines(lines)
                else:
                    print(filename)        
 
if __name__ == "__main__":                    
    path = os.path.abspath(os.path.join(os.getcwd(), "../../"))
    folder = os.path.join(path,"FAT_Regression")
    add_case_id(folder)